package com.sweets.look.ui.browser;

import android.os.Environment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import com.sweets.look.preference.PreferenceManager;
import com.sweets.look.util.BrowserUtils;
import com.sweets.look.util.LogUtils;

public class AdBlock {
    private static final String TAG = AdBlock.class.getSimpleName();
    private static final String BLOCKED_DOMAINS_LIST_FILE_NAME = "hosts.txt";
    private static final String COMMENT = "#";
    private static final String EMPTY = "";
    private static final String LOCALHOST = "localhost";
    private static final String LOCAL_IP_V4 = "127.0.0.1";
    private static final String LOCAL_IP_V4_ALT = "0.0.0.0";
    private static final String LOCAL_IP_V6 = "::1";
    private static final String SPACE = " ";
    private static final String TAB = "\t";
    private static final String[] adBlockTag = new String[]{"tuijianindex?uid=", "baidu.com/api/proxyapi?", ".js?advertID=",
            "/ad.gif", "/images_ad/", "/images/ad_", "/js/ads/", "/ad_js/", "/ads/", "/ad/"};

    private static final String[] adWhiteTag = new String[]{"adblock"};
    private boolean mBlockAds;
    private static final Set<String> mBlockedDomainsList = new HashSet();
    private static AdBlock mInstance;
    private boolean mLocalAdBlock;
    private static final Locale mLocale = Locale.getDefault();
    private final PreferenceManager mPreferences;
    private static final Set<String> mWhiteDomainsList = new HashSet();


    private AdBlock() {
        super();
        if (mBlockedDomainsList.isEmpty()) {
            this.loadBlockedDomainsList();
        }

        if (mWhiteDomainsList.isEmpty()) {
            this.loadWhiteDomainsList();
        }

        this.mPreferences = PreferenceManager.getInstance();
        this.mBlockAds = this.mPreferences.getAdBlockEnabled();
        this.mLocalAdBlock = this.mPreferences.getLocalAdBlockEnabled();
    }


    public static AdBlock getInstance() {
        if (AdBlock.mInstance == null) {
            AdBlock.mInstance = new AdBlock();
        }

        return AdBlock.mInstance;
    }

    public boolean isAd(String url) {
        if (this.mBlockAds && url != null) {
            String dmoainName = BrowserUtils.getDomainName(url);
            String realDomainName = BrowserUtils.getRealDomainName(url);
            if (url.contains("://")) {
                url = url.substring(url.indexOf("://") + 3);
            }

            //白名单
            for (int i = 0; i < adWhiteTag.length; i++) {
                if (url.contains(adWhiteTag[i])) {
                    return false;
                }
            }
            //广告标签
            for (int i = 0; i < adBlockTag.length; i++) {
                if (url.contains(adBlockTag[i])) {
                    return true;
                }
            }

            if (((mWhiteDomainsList.contains(dmoainName.toLowerCase(mLocale))) ||
                    !mBlockedDomainsList.contains(dmoainName.toLowerCase(mLocale))) &&
                    (!mBlockedDomainsList.contains(realDomainName.toLowerCase(mLocale)) ||
                            (mWhiteDomainsList.contains(realDomainName.toLowerCase(mLocale))))) {
                if (!mBlockedDomainsList.contains(url.toLowerCase(mLocale))) {
                    return false;
                }

                if (mWhiteDomainsList.contains(url.toLowerCase(mLocale))) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }

    private void loadBlockedDomainsList() {
        this.loadDefaultBlockDomainsList();
        if (!this.mLocalAdBlock) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        InputStreamReader v4 = new InputStreamReader(new FileInputStream(new File(Environment
                                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                                "hosts.txt")), "UTF-8");
                        BufferedReader v5 = new BufferedReader(((Reader) v4));
                        String v3;
                        while ((v3 = v5.readLine()) != null) {
                            if (v3.isEmpty()) {
                                continue;
                            }

                            if (v3.startsWith("#")) {
                                continue;
                            }

                            v3 = v3.replace("127.0.0.1", "").replace("0.0.0.0", "").replace("::1", "")
                                    .replace("\t", "");
                            int v0 = v3.indexOf("#");
                            if (v0 >= 0) {
                                v3 = v3.substring(0, v0);
                            }

                            v3 = v3.trim();
                            if (v3.isEmpty()) {
                                continue;
                            }

                            if (v3.equals("localhost")) {
                                continue;
                            }
                            while (v3.contains(" ")) {
                                int v6 = v3.indexOf(" ");
                                AdBlock.mBlockedDomainsList.add(v3.substring(0, v6).trim());
                                v3 = v3.substring(v6, v3.length()).trim();
                            }

                            AdBlock.mBlockedDomainsList.add(v3.trim());
                        }

                        LogUtils.w(TAG, "loading block list");
                        v4.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    private void loadDefaultBlockDomainsList() {
        String[] blocks = new String[]{"njs.hcm94alliance.com", "polkoa.com", "s.456juhd.com", "cpro.baidustatic.com",
                "js.chinaheh.com", "oki.xcyjzs.net", "www.hbtlwl.com", "js.goodemc.com", "ima.xcyjzs.net",
                "s.sscefsol.com", "c.dokrmob.com", "tu.bolimubei.com", "cg.bigbos.top", "imgcdn.xixiwan.net",
                "ms.liuliguo.com", "tu.miliqiji.com", "njs.reliancevalve.com", "abc.goodemc.com", "qd.maskbaby.com.cn",
                "s4.0594003.com", "vip.koukou7.com", "koukou7.com", "m1bgt01.nokia333.com", "s2.0594003.com",
                "www.google-analytics.com", "img.aahtek.com", "googleads.g.doubleclick.net", "cm.g.doubleclick.net",
                "pagead2.googlesyndication.com", "rwq.youle55.com", "img.twcczhu.com", "static.googleadsserving.cn",
                "kwflvcdn.000dn.com", "c.f1zd.com", "slb.sushouge.com", "a.xhnlf.com", "img.shentus.com",
                "www.51vipedu.com", "s1.keytui.com"};

        int i = 0;
        while (i < blocks.length) {
            mBlockedDomainsList.add(blocks[i]);
            ++i;
        }
    }

    private void loadWhiteDomainsList() {

        String[] blocks = new String[]{"bzclk.baidu.com", "a.union.mi.com", "redirect.simba.taobao.com",
                "static.360buyimg.com", "img30.360buyimg.com", "ecmb.bdimg.com", "re.m.taobao.com",
                "mclick.simba.taobao.com", "y3.ifengimg.com", "ai.m.taobao.com", "s.click.taobao.com",
                "down.360safe.com", "dd.myapp.com", "a.gdown.baidu.com", "m.shouji.360tpcdn.com", "pp.myapp.com",
                "game.weixin.qq.com", "as.baidu.com", "appsearchcdn.baidu.com", "bcscdn.baidu.com"};

        int i = 0;
        while (i < blocks.length) {
            mWhiteDomainsList.add(blocks[i]);
            ++i;
        }
    }

    public void updatePreference() {
        if (this.mBlockAds != this.mPreferences.getAdBlockEnabled()
                || this.mLocalAdBlock != this.mPreferences.getLocalAdBlockEnabled()) {
            this.mBlockAds = this.mPreferences.getAdBlockEnabled();
            this.mLocalAdBlock = this.mPreferences.getLocalAdBlockEnabled();
            this.loadBlockedDomainsList();
        }
    }
}

